 package com.joycessh.dao;
 
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;

//Hibernate服务提供者
public class HibernateServiceProvider {
	private static SessionFactory sessionFactory = null;	
//配置文件中注册的是映射文件,调用Configuration()方法：
	private static Configuration configuration = new Configuration();

//配置文件中注册的是注释映射PO类,调用AnnotationConfiguration()方法：
//private static Configuration configuration = new AnnotationConfiguration();   

    //构造方法	
	public HibernateServiceProvider()
	{
		initHibernate();
	}    

    //初始化sessionFactory实例：
	public static synchronized void initHibernate() throws HibernateException
	{    
    	if(sessionFactory == null)
    	try {
    			configuration.configure();   //启动hibernate    			
    			sessionFactory = configuration.buildSessionFactory();       		
    		} catch (HibernateException he) 
    		{
    			System.err.println(" Error Creating SessionFactory ");
    			throw he;
    		}    		
    }	
	
    //重新创建SessionFactory实例
	public static void rebuildSessionFactory() throws HibernateException
	{
		try {
			configuration.configure();
			sessionFactory = configuration.buildSessionFactory();
		} catch (HibernateException he) {
			System.err.println(" Error Creating SessionFactory ");
			throw he;
		}
	}
	
    //获取Session实例
	public Session getSession() throws HibernateException {
		if (sessionFactory == null) 
		{
			rebuildSessionFactory();
		}
		Session session = sessionFactory.openSession();
        return session;
    }
	
	public void closeSessionFactory() throws HibernateException
	{
		sessionFactory.close();
	}
}